package cn.wolfcode.luowowo2.articleserver.service.imp;
import cn.wolfcode.luowowo2.article.domain.Travel;
import cn.wolfcode.luowowo2.article.domain.TravelContent;
import cn.wolfcode.luowowo2.article.mapper.TravelContentMapper;
import cn.wolfcode.luowowo2.article.mapper.TravelMapper;
import cn.wolfcode.luowowo2.article.service.ITravelService;
import cn.wolfcode.luowowo2.common.query.TravelQueryObject;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

/**
 * Created by Albert on 2019/7/9.
 */
@Service
public class TravelServiceImpl implements ITravelService{
    @Autowired
    private TravelMapper mapper;
    @Autowired
    TravelContentMapper travelContentMapper;
    @Override
    public PageInfo<Travel> query(TravelQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderString());
        List<Travel> list = mapper.selectForList(qo);
        return new PageInfo<>(list);
    }

    @Override
    public Travel get(Long id) {
        Travel travel = mapper.selectByPrimaryKey(id);
        TravelContent travelContent = travelContentMapper.get(id);
        travel.setTravelContent(travelContent);
        return travel;
    }

    @Override
    public List<Travel> getByViewNumTop3(Long id) {
        return mapper.selectByViewNumTop3(id);
    }

    @Override
    public Long saveOrUpdate(Travel travel) {
        String content = travel.getTravelContent().getContent();
        if (content.length()>200) {
            travel.setSummary(content.substring(0,200));
        }else{
            travel.setSummary(content);
        }
        if (travel.getId()==null) {
            travel.setCreateTime(new Date());
            travel.setLastUpdateTime(new Date());
            mapper.insert(travel);
            TravelContent travelContent = travel.getTravelContent();
            travelContent.setId(travel.getId());
            travelContentMapper.insert(travelContent);
        }else{
            travel.setLastUpdateTime(new Date());
            mapper.updateByPrimaryKey(travel);
            TravelContent travelContent = travel.getTravelContent();
            travelContent.setId(travel.getId()); //需要注意内部对象的id问题
            travelContentMapper.update(travelContent);
        }
        return travel.getId();
    }

    @Override
    public List<Travel> list() {
        return mapper.selectAll();
    }

}
